/**
 * Copyright (c) 2017-2018,Retire 吴益峰 (372310383@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jplus.admin.controller;

import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Ret;
import io.jboot.components.rpc.annotation.RPCInject;
import io.jboot.web.controller.annotation.RequestMapping;
import io.jplus.JplusConsts;
import io.jplus.admin.model.Dept;
import io.jplus.admin.service.DeptService;
import io.jplus.core.web.base.BaseController;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import java.util.List;

@RequestMapping(value = "/admin/dept", viewPath = JplusConsts.BASE_VIEW_PATH + "admin")
public class DeptController extends BaseController {

    @RPCInject
    DeptService deptService;

    public void index() {
        render("dept.html");
    }

    @RequiresPermissions("sys:dept:list")
    public void list() {
        List<Dept> deptList = deptService.queryList(getQuery());
        renderJson(JsonKit.toJson(deptList));
    }

    @RequiresPermissions("sys:dept:info")
    public void info() {
        String deptId = getPara();
        if (deptId == null) {
            renderJsonForFail("id不能为空！");
            return;
        }
        Dept dept = deptService.findDeptById(deptId);
        renderJson(Ret.ok("dept", dept));
    }

    @Before(POST.class)
    @RequiresPermissions("sys:dept:save")
    public void save() {
        Dept dept = jsonToModel(Dept.class);
        deptService.save(dept);
        renderJsonForSuccess();
    }

    @Before(POST.class)
    @RequiresPermissions("sys:dept:update")
    public void update() {
        Dept dept = jsonToModel(Dept.class);
        boolean tag = deptService.update(dept);
        if (tag) {
            renderJsonForSuccess();
        } else {
            renderJsonForFail("更新失败！");
        }
    }

    @RequiresPermissions("sys:dept:delete")
    public void delete(Long deptId) {
        if (deptId == null) {
            renderJsonForFail("id不能为空！");
            return;
        }
        boolean tag = deptService.deleteById(deptId);
        if (tag) {
            renderJsonForSuccess();
        } else {
            renderJsonForFail("删除失败！");
        }
    }

    @RequiresPermissions("sys:dept:select")
    public void select() {
        List<Dept> deptList = deptService.findAll();
        renderJson(Ret.ok("deptList", deptList));
    }

}
